package cn.spike.pet.service.impl;

import cn.spike.basic.exception.BusinessException;
import cn.spike.basic.service.IBaiduAiAuditService;
import cn.spike.basic.util.*;
import cn.spike.order.domain.OrderPetAcquisition;
import cn.spike.order.mapper.OrderPetAcquisitionMapper;
import cn.spike.org.domain.Employee;
import cn.spike.org.domain.Shop;
import cn.spike.org.mapper.EmployeeMapper;
import cn.spike.org.mapper.ShopMapper;
import cn.spike.pet.domain.SearchMasterMsg;
import cn.spike.pet.domain.SearchMasterMsgAuditLog;
import cn.spike.pet.dto.MsgDto;
import cn.spike.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.spike.pet.mapper.SearchMasterMsgMapper;
import cn.spike.pet.query.SearchMasterMsgQuery;
import cn.spike.pet.service.ISearchMasterMsgService;
import cn.spike.basic.service.impl.BaseServiceImpl;
import cn.spike.user.domain.Logininfo;
import cn.spike.user.domain.User;
import cn.spike.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //空值校验
        if(StringUtils.isEmpty(msg.getTitle()) || StringUtils.isEmpty(msg.getName())
                || StringUtils.isEmpty(msg.getAddress())){
            return new AjaxResult(false,"寻主消息不能为空!!");
        }

        //获取消息发布人
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());

        //为寻主消息添加userid发布人的id - 添加寻主消息进数据库
        msg.setUserId(user.getId());
        searchMasterMsgMapper.add(msg);

        //审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + "," + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());

        //创建返回值对象
        AjaxResult ajaxResult = new AjaxResult();

        //创建审核日志对象 - 并设置寻主消息id
        SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(msg.getId());
        //如果审核通过
        if(boo1 && boo2){
            //获取用户所在地址的点
            Point point = DistanceUtils.getPoint(msg.getAddress());
            //找到离用户最近的店铺
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            //如果五十公里内有店铺
            if(nearestShop != null){
                //修改寻主消息状态
                msg.setState(1);
                //设置最近的店铺id
                msg.setShopId(nearestShop.getId());
                //给店铺发短信
                //SmsUtils.sendSms(nearestShop.getTel(),"有寻主订单,位于:"+msg.getAddress()+"请及时前往处理");
                System.out.println("有寻主订单,位于:"+msg.getAddress()+"请及时前往处理");
            }else {//如果五十公里内没有店铺
                //修改寻主消息状态 - 放入寻主池
                msg.setState(3);
                //给发布用户发短信
                //SmsUtils.sendSms(user.getPhone(),"您的附近没有合适店铺,请耐心等待");
                System.out.println("寻主消息发布成功,您的附近没有合适店铺,请耐心等待");
            }
            log.setState(1);   //修改审核日志状态 - 审核成功
            log.setNote("审核成功");
            ajaxResult.setMsg("寻主消息发布成功");
            searchMasterMsgMapper.update(msg);
        }else {//审核不通过
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgMapper.delete(msg.getId());
            ajaxResult.setMsg("发布失败,寻主消息有违规字段,请重新发布").setSuccess(false);
        }
        searchMasterMsgAuditLogMapper.add(log);
        return ajaxResult;
    }

    /**
     * 用户查询自己的所有寻主
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    /**
     * 后台查询待处理的
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //设置寻主消息状态
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee =  employeeMapper.loadByLogininfoId(logininfo.getId());
        //如果有shopid - 说明店铺管理员 - 只能查看自己店铺的寻主消息
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 查询已完成的寻主消息
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //设置寻主消息状态
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee =  employeeMapper.loadByLogininfoId(logininfo.getId());
        //如果有shopid - 说明店铺管理员 - 只能查看自己店铺的寻主消息
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 查询寻主池里的消息
     * @param query
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query) {
        query.setState(3);
        return super.pageQuery(query);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    @Transactional
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param msgDto
     */
    @Override
    @Transactional
    public void accept(MsgDto msgDto) {
        List<OrderPetAcquisition> oders =  orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        //判单此寻主消息是否已经产生订单 并且正在处理中
        if(oders!=null){
            for (OrderPetAcquisition order : oders) {
                if(order.getState()==0){
                    throw new BusinessException("订单正在处理中,请勿重复接单！！");
                }
            }
        }
        //生成宠物收购订单 - 添加数据库
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition order = creatOrderPetAcquisition(msgDto,msg);
        orderPetAcquisitionMapper.add(order);

        //给处理人发送短信 - 告知处理
        Employee employee = employeeMapper.loadById(msgDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单,请在两天之前前往:"+msg.getAddress()+"收购宠物");
        System.out.println(employee.getPhone()+"你有新的订单,请在两天之前前往:"+msg.getAddress()+"收购宠物");

    }

    private OrderPetAcquisition creatOrderPetAcquisition(MsgDto msgDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //设置订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        //userId shopId address price
        BeanUtils.copyProperties(msg,order);
        //设置支付方式 - 垫付
        //order.setPaytype(0);
        //设置状态待处理
        order.setState(0);
        //设置摘要
        order.setDigest(msgDto.getNote());
        //设置寻主消息ID
        order.setSearchMasterMsgId(msg.getId());
        //设置处理人ID
        order.setEmpId(msgDto.getHandler());
        //设置两天订单过期时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        return order;
    }
}
